package com.doupi.partner.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * XML UTILS，用于javabean和xml之间互相转换ßßßß
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年10月24日 下午11:39:13
 */
public class XmlUtils {

	private final static Logger LOGGER = LoggerFactory.getLogger(XmlUtils.class);

	/**
	 * javabena转xml
	 */
	public static <T> String convertToXml(T obj) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			marshaller.marshal(obj, os);
			return os.toString();
		} catch (Exception e) {
			LOGGER.error("javaBean转XML失败", e);
		}
		return null;
	}

	/**
	 * XML转JAVA BEAN
	 */
	@SuppressWarnings("unchecked")
	public static <T> T convertFromXml(String xml, Class<T> clazz) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
			Object obj = unmarshaller.unmarshal(is);
			return (T) obj;
		} catch (Exception e) {
			LOGGER.error("XML转javaBean失败", e);
		}
		return null;
	}
}
